from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.views import View


import json
from app1.models import User


#导入内置序列化类
from django.core.serializers import serialize

# drf类视图
from rest_framework.response import Response
from rest_framework.views import APIView
from .mysev import UserSev


# 导入加密库
import hashlib



# 方法视图
def myindex(request):

    # 读库
    res = User.objects.all()
    # 手动序列化
    mylist = json.loads(serialize('json',res,ensure_ascii=False))
    # 返回json数据
    return JsonResponse(mylist,safe=False,json_dumps_params={'ensure_ascii':False})

    # return HttpResponse('这里是首页')

# drf类视图
class MyUser(APIView):
    def get(self,request):
        # 读库
        users = User.objects.all()
        # 序列化
        user_ser = UserSev(users,many=True)
        # 返回json数据
        return Response(user_ser.data)

# 类视图
class MyView(View):
    def get(self,request):
        return HttpResponse('你好')

# 模板练习
def mytem(request):
    title = 'Hello Django'
    num = 100
    li = [1,2,3]
    dic = {'name':'123','age':12}

    # 读库
    res = User.objects.all()

    return render(request,'test.html',locals())





class Add(View):
    def get(self,request):
        return render(request,'add_user.html')
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        img = request.FILES.get('img')
        type = request.POST.get('type')
        User.objects.create(username=username,password=password,img=img,type=type)
        mes = '666'
        return redirect('/all/')

class All(View):
    def get(self,request):
        user = User.objects.all()
        return render(request,'add_all.html',locals())

class Upload(View):
    def get(self,request):
        id_ = request.GET.get('id')
        users = User.objects.filter(pk=id_)
        return render(request,'upload.html',locals())
    def post(self,request):
        id_ = request.GET.get('id')
        username=request.POST.get('username')
        password=request.POST.get('password')
        type=request.POST.get('type')
        User.objects.filter(pk=id_).update(username=username,password=make_password(password),type=type)

        return redirect('/all/')




class Delete(View):
    def get(self,request):
        id_=request.GET.get('id')
        User.objects.get(pk=id_).delete()
        return redirect('/all/')




# 加密方法
def make_password(mypass):

    # md5
    mypass = hashlib.md5()
#      对字符串进行编译（加盐操作）
    mypass.update('456'.encode(encoding='utf-8'))
    # 返回密文
    return mypass.hexdigest()



a = ""

from .utils import *
from .utils.captcha.captcha import captcha
def getimg(request):

    global a

    name, text,image = captcha.generate_captcha()
    res = HttpResponse(image,content_type='image/png')

    a = text


    return res













# 注册接口
class Register(APIView):
    def get(self,request):

        global a

        # 接受参数
        username = request.GET.get('username','未收到')
        password = request.GET.get('password','未收到密码')
        password2 = request.GET.get('password2','未收到密码')
        image = request.GET.get('image','未收到密码')

        print(a)
        print(image)


        if not a == image:
            res = {}
            res['code'] = 405
            res['message'] = '验证码错误'
            return Response(res)
        else:

            # 排重操作
            user = User.objects.filter(username=username).first()
            if user:
                res = {}
                res['code'] = 405
                res['message'] = '用户名或密码错误'
                return Response(res)
            else:
                if password2 != password:
                    res = {}
                    res['code'] = 404
                    res['message'] = '两次密码不一致'
                    return Response(res)
                elif not all([username,password,password2]):
                    res = {}
                    res['code'] = 406
                    res['message'] = '信息不完整'
                    return Response(res)
                else:

                    # 进行入库逻辑 密码加密
                    user = User(username=username, password=make_password(password2), type=0)

                    # 保存
                    user.save()

                    # 返回结果
                    res = {}
                    res['code'] = 200
                    res['message'] = '注册成功'
                    return Response(res)














# 登录接口
class Login(APIView):
    def post(self,request):
        username = request.POST.get('username','未收到')
        password = request.POST.get('password','未收到密码')

        # 查询数据
        user = User.objects.filter(username=username,password=make_password(password)).first()
        if user:
            # 返回结果
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['username'] = user.username
            return Response(res)

        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或密码错误'
            return Response(res)




